package netty;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.util.Date;

public class TimeServerHandler extends ChannelInboundHandlerAdapter {

    /**
     * 当客户端发送了请求之后，channelRead方法会被回调。参数ChannelHandlerContext包含了当前发送请求的客户端的一些上下文信息，msg表示客户端发送的请求信息
     *
     * @param ctx
     * @param msg
     * @throws Exception
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { // 1
        System.out.println("=======channelRead========" + this.getClass().getName());
        String request = (String) msg; //2
        String response = null;
        if ("QUERY TIME ORDER".equals(request)) { // 3
            response = new Date(System.currentTimeMillis()).toString();
        } else {
            response = "BAD REQUEST";
        }
        response = response + System.getProperty("line.separator"); // 获取系统的分隔符，windows:\r\n linux:\n
        ByteBuf resp = Unpooled.copiedBuffer(response.getBytes()); // 5
        ctx.writeAndFlush(resp); // 6
    }
}